package com.thermofisher.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.thermofisher.beans.*;
import com.thermofisher.service.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class B1000SYNC
{

    private final Logger logger = LoggerFactory.getLogger(B1000SYNC.class);

    @Resource
    private ConfigService configService;

    @Resource
    private ChanceInfoService chanceInfoService;

    @Resource
    private CustomerService customerService;

    @Resource
    private EstimateService estimateService;

    @Resource
    private ProjectService projectService;

    @Resource
    private SupportRequireService supportRequireService;

    @Resource
    private UserService userService;

    @Resource
    private EmailRecordService emailRecordService;

    @Resource
    private ProjectProductService projectProductService;

    @Resource
    private B100Http b100Http;

    public void update()
    {
        Config config = init();
        String haveExe = config.getValue();
        String toExe = getNow();
        String haveExe2 = haveExe.replace("T", "").replace("Z", "");
        String toExe2 = toExe.replace("T", "").replace("Z", "");
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
        Date date1 = null;
        Date date2 = null;
        try
        {
            date1 = dateFormat.parse(haveExe2);
            date2 = dateFormat.parse(toExe2);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        int i = 2;
        String trueExe = pulus(date1, i);
        if (date2.getTime() - date1.getTime() >= 2 * i * 60 * 60 * 1000)
        {
            execute(config, trueExe);
        }

    }

    private String pulus(Date toExeDateDate, int i)
    {
        long toExeLong = toExeDateDate.getTime() + (i * 60 * 60 * 1000);
        Date toExeDate = new Date(toExeLong);

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
        String toExe = format.format(toExeDate);
        String trueExe = toExe.substring(10, 12);
        int time = Integer.parseInt(trueExe);
        if (time >= 10)
        {
            toExe = toExe.substring(0, 10) + "T" + time + ":00:00Z";
        }
        else
        {
            toExe = toExe.substring(0, 10) + "T" + "0" + time + ":00:00Z";
        }
        return toExe;
    }

    private void execute(Config config, String toExe)
    {
        try
        {
            executeDetail(toExe);
            updateConfig(config, toExe);
            configService.saveOrUpdate(config);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            logger.error("定时任务B1000SYNC执行失败");

        }
    }

    private void executeDetail(String toExe)
    {
        int i = 0;
        String accessToken = getToken();
        while (i < 3)
        {
            if (StringUtils.isEmpty(accessToken))
            {
                accessToken = getToken();
            }
            i++;
        }

        //List<Customer> customerList = getCustomerList(accessToken, toExe);
        List<Estimate> estimateList = getEstimateList(accessToken, toExe);
        List<Project> projectList = getProjectList(accessToken, toExe);
        List<SupportRequire> supportRequireList = getSupportRequireList(accessToken, toExe);
        List<User> userList = getUserList(accessToken, toExe, projectList);
        List<ChanceInfo> chanceInfoList = getChanceInfoList(accessToken, projectList);
        List<ProjectProduct> projectProductList = getProjectProductList(accessToken, projectList);

        List<SupportRequire> supportRequireList2 = new ArrayList();
        for (SupportRequire supportRequire : supportRequireList)
        {
            if (!StringUtils.isEmpty(supportRequire.getProjectId()))
            {
                supportRequireList2.add(supportRequire);
            }
        }

        List<ProjectProduct> projectProductList2 = new ArrayList();
        for (ProjectProduct projectProduct : projectProductList)
        {
            if (!StringUtils.isEmpty(projectProduct.getProductNo()))
            {
                projectProductList2.add(projectProduct);
            }
        }
        sendEmail(projectList, userList);

        findProjects(projectList);
        projectService.saveOrUpdateBatch(projectList);

        findOthers(estimateList, supportRequireList2, userList,
                   projectProductList2);

        estimateService.saveOrUpdateBatch(estimateList);
        supportRequireService.saveOrUpdateBatch(supportRequireList2);
        userService.saveOrUpdateBatch(userList);
        if (!ObjectUtils.isEmpty(chanceInfoList))
        {
            chanceInfoService.saveOrUpdateBatch(chanceInfoList);
            chanceInfoService.flushProjectNo();
        }
        projectProductService.saveOrUpdateBatch(projectProductList2);
        projectProductService.flushProjectNo();
        //customerService.saveOrUpdateBatch(customerList3);
        logger.info("入库完毕");
        //throw new RuntimeException("");
    }

    private void findOthers(List<Estimate> estimateList,
                            List<SupportRequire> supportRequireList, List<User> userList,
                            List<ProjectProduct> projectProductList)
    {

        for (Estimate estimate : estimateList)
        {
            Estimate estimate2 = estimateService.getOne(Wrappers.<Estimate>lambdaQuery()
                                                                .eq(Estimate::getProjectNo,
                                                                    estimate.getProjectNo())
                                                                .eq(Estimate::getDepartmentNo,
                                                                    estimate.getDepartmentNo()));
            if (!ObjectUtils.isEmpty(estimate2))
            {
                estimate.setId(estimate2.getId());
            }
        }
        for (SupportRequire supportRequire : supportRequireList)
        {
            SupportRequire supportRequire2 = supportRequireService
                    .getOne(Wrappers.<SupportRequire>lambdaQuery()
                                    .eq(SupportRequire::getProjectId,
                                        supportRequire.getProjectId()).eq(SupportRequire::getSeq,
                                                                          supportRequire.getSeq()));
            if (!ObjectUtils.isEmpty(supportRequire2))
            {
                supportRequire.setId(supportRequire2.getId());
            }
        }

        for (User user : userList)
        {
            List <User> userList2 = userService.list(Wrappers.<User>lambdaQuery()
                    .eq(User::getProjectNo, user.getProjectNo())
                    .eq(User::getDepartmentCode,
                            user.getDepartmentCode()));
            if(!ObjectUtils.isEmpty(userList2)&&userList2.size()>=2){
                userService.remove(Wrappers.<User>lambdaQuery()
                        .eq(User::getProjectNo, user.getProjectNo())
                        .eq(User::getDepartmentCode,
                                user.getDepartmentCode()));
            }

            User user2 =
                    userService.getOne(Wrappers.<User>lambdaQuery()
                                               .eq(User::getProjectNo, user.getProjectNo())
                                               .eq(User::getDepartmentCode,
                                                   user.getDepartmentCode()));
            if (!ObjectUtils.isEmpty(user2))
            {
                user.setId(user2.getId());
            }
        }
        for (ProjectProduct projectProduct : projectProductList)
        {
            ProjectProduct projectProduct2 = projectProductService
                    .getOne(Wrappers.<ProjectProduct>lambdaQuery()
                                    .eq(ProjectProduct::getProjectId,
                                        projectProduct.getProjectId())
                                    .eq(ProjectProduct::getProductNo,
                                        projectProduct.getProductNo()));
            if (!ObjectUtils.isEmpty(projectProduct2))
            {
                projectProduct.setId(projectProduct2.getId());
            }
        }
    }

    private void findProjects(List<Project> projectList)
    {
        for (Project project : projectList)
        {
            Project project2 = projectService.getOne(Wrappers.<Project>lambdaQuery()
                                                             .eq(Project::getProjectNo,
                                                                 project.getProjectNo()));
            if (!ObjectUtils.isEmpty(project2))
            {
                project.setId(project2.getId());
            }
        }
    }

    private void sendEmail(List<Project> projectList, List<User> userList)
    {
        List<EmailRecord> emailRecordsList = new ArrayList();
        List<Config> configList = configService.getAllEmail();
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = format.format(date);
        for (Project project : projectList)
        {
            String status = "初审通过,立项完成";
            if (StringUtils.isEmpty(project.getApproveStatus()) ||
                    status.indexOf(project.getApproveStatus()) == -1)
            {
                continue;
            }
            List<EmailRecord> emailRecordList = emailRecordService
                    .list(Wrappers.<EmailRecord>lambdaQuery()
                                  .eq(EmailRecord::getProjectNo, project.getProjectNo()));
            if (!ObjectUtils.isEmpty(emailRecordList))
            {
                continue;
            }
            for (Config config : configList)
            {
                EmailRecord emailRecord = new EmailRecord();
                emailRecord.setCreateDate(dateString);
                emailRecord.setUpdateDate(project.getLastModifiedDate());
                emailRecord.setProjectNo(project.getProjectNo());
                emailRecord.setProjectName(project.getProjectName());
                emailRecord.setStatusChange(project.getApproveStatus());
                emailRecord.setDescription("");
                emailRecord.setTemplate("template1");
                emailRecord.setSendStatus(0);
                emailRecord.setTimes(0);
                emailRecord.setAliaName(config.getRemark());
                emailRecord.setEmail(config.getValue());
                emailRecordsList.add(emailRecord);
            }
            if (StringUtils.equals("立项完成", project.getApproveStatus()))
            {
                for (User user : userList)
                {
                    if (StringUtils.isEmpty(user.getEmail()))
                    {
                        continue;
                    }
                    if (StringUtils.equals(user.getProjectNo(), project.getProjectNo()))
                    {
                        EmailRecord emailRecord = new EmailRecord();
                        emailRecord.setCreateDate(dateString);
                        emailRecord.setUpdateDate(project.getLastModifiedDate());
                        emailRecord.setProjectNo(project.getProjectNo());
                        emailRecord.setProjectName(project.getProjectName());
                        emailRecord.setStatusChange(project.getApproveStatus());
                        emailRecord.setDescription("");
                        emailRecord.setTemplate("template1");
                        emailRecord.setSendStatus(0);
                        emailRecord.setTimes(0);
                        emailRecord.setAliaName(user.getName());
                        emailRecord.setEmail(user.getEmail());
                        emailRecordsList.add(emailRecord);
                    }
                }
            }
        }
        emailRecordService.saveBatch(emailRecordsList);
    }

    private List<ProjectProduct> getProjectProductList(String accessToken,
                                                       List<Project> projectList)
    {
        List list = new ArrayList();

        int i = 0;
        String ids = "";
        for (Project project : projectList)
        {
            if (StringUtils.isEmpty(project.getProjectId()))
            {
                continue;
            }
            i++;
            if (i == 1)
            {
                ids += "'" + project.getProjectId() + "'";
            }
            else
            {
                ids += ",'" + project.getProjectId() + "'";
            }
        }
        String url =
                "https://cs76.salesforce.com/services/data/v37.0/query/?q=select+ Id,material_Description__c,Project_name__c, Name ,act_winrate__c, Phase__c , Application__c , model__r.name , Model__c , Division__c , est_Quantity__c ,est_amount__c , Competitor__c , Booking__c , Revenue__c+from+B1000_project_product__c+where+Project_Name__c+in(" +
                        ids + ")";
        String message = b100Http.getData(url, accessToken);
        logger.info("ProjectProductList数据:" + message);
        JSONObject jsonObject = (JSONObject) JSONObject.parse(message);
        JSONArray jsonArray = jsonObject.getJSONArray("records");
        for (Object object : jsonArray)
        {
            ProjectProduct projectProduct = new ProjectProduct();
            JSONObject jsonObject1 = (JSONObject) object;
            projectProduct.setProjectId(jsonObject1.getString("Project_name__c"));
            projectProduct.setProductNo(jsonObject1.getString("Name"));
            projectProduct.setProductName(jsonObject1.getString("Project_name__c"));
            projectProduct.setPhase(jsonObject1.getString("Phase__c"));
            projectProduct.setApplication(jsonObject1.getString("Application__c"));
            if (!ObjectUtils.isEmpty(jsonObject1.getJSONObject("Model__r")))
            {
                projectProduct
                        .setSpecificApplication(
                                jsonObject1.getJSONObject("Model__r").getString("Name"));

            }
            projectProduct.setModel(jsonObject1.getString("Model__c"));
            projectProduct.setDivision(jsonObject1.getString("Division__c"));
            if (!StringUtils.isEmpty(jsonObject1.getString("est_Quantity__c")))
            {
                projectProduct.setQuantity(jsonObject1.getString("est_Quantity__c"));
            }

            BigDecimal bigdecimal = new BigDecimal(jsonObject1.getString("est_amount__c"));
            BigDecimal bigDecimal = new BigDecimal(jsonObject1.getString("est_Quantity__c"));
            BigDecimal salePrice = bigdecimal.divide(bigDecimal, 2, BigDecimal.ROUND_HALF_UP);
            projectProduct.setSalesPrice(String.valueOf(salePrice));
            projectProduct.setTotalPrice(jsonObject1.getString("est_amount__c"));
            projectProduct.setCompetitor(jsonObject1.getString("Competitor__c"));
            projectProduct.setOtherCompetitor(jsonObject1.getString("Competitor__c"));
            //projectProduct.setWinrate(new Double(jsonObject1.getString("act_winrate__c")));
            projectProduct.setMethodSales(jsonObject1.getString(""));
            projectProduct.setBooking(jsonObject1.getString("Booking__c"));
            projectProduct.setTurnOver(jsonObject1.getString("Revenue__c"));
            list.add(projectProduct);
        }

        return list;
    }

    private List<SupportRequire> getSupportRequireList(String accessToken, String toExe)
    {
        String url =
                "https://cs76.salesforce.com/services/data/v37.0/query/?q=select+ Id, Project_name__c , Name,First_require__c,First_support__c, Seco_require__c,Seco_support__c,Third_require__c,Third_support__c+from+B1000_project__c+where+LastModifiedDate+%3E%3D+" +
                        toExe;
        String message = b100Http.getData(url, accessToken);
        logger.info("SupportRequireList数据:" + message);
        JSONObject jsonObject = JSONObject.parseObject(message);
        List list = new ArrayList();
        JSONArray jsonArray = jsonObject.getJSONArray("records");
        for (int i = 0; i < jsonArray.size(); i++)
        {
            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
            SupportRequire supportRequire = new SupportRequire();
            String id = jsonObject1.getString("Id");
            supportRequire.setProjectId(id);
            supportRequire.setSupport(jsonObject1.getString("First_support__c"));
            supportRequire.setRequired(jsonObject1.getString("First_require__c"));
            supportRequire.setSeq("1");
            list.add(supportRequire);
            SupportRequire supportRequire2 = new SupportRequire();
            supportRequire2.setProjectId(id);
            supportRequire2.setSupport(jsonObject1.getString("Seco_support__c"));
            supportRequire2.setRequired(jsonObject1.getString("Seco_require__c"));
            supportRequire2.setSeq("2");
            list.add(supportRequire2);
            SupportRequire supportRequire3 = new SupportRequire();
            supportRequire3.setProjectId(id);
            supportRequire3.setSupport(jsonObject1.getString("Third_support__c"));
            supportRequire3.setRequired(jsonObject1.getString("Third_require__c"));
            supportRequire3.setSeq("3");
            list.add(supportRequire3);
        }
        return list;
    }

    private List<ChanceInfo> getChanceInfoList(String accessToken, List<Project> projectList)
    {
        List list = new ArrayList();
        int i = 0;
        String ids = "";
        for (Project project : projectList)
        {
            if (StringUtils.isEmpty(project.getProjectId()))
            {
                continue;
            }
            i++;
            if (i == 1)
            {
                ids += "'" + project.getProjectId() + "'";
            }
            else
            {
                ids += ",'" + project.getProjectId() + "'";
            }
        }
        String url =
                "https://cs76.salesforce.com/services/data/v37.0/query/?q=select+ Name, StageName, Probability, CloseDate, Project_Name__c , Amount,Amount_USD__c, SO_no__c +from+opportunity+where+Project_Name__c+in(" +
                        ids + ")";
        String message = b100Http.getData(url, accessToken);
        logger.info("ChanceInfoList数据:" + message);
        JSONObject jsonObject = (JSONObject) JSONObject.parse(message);

        JSONArray jsonArray = jsonObject.getJSONArray("records");
        for (Object object : jsonArray)
        {
            ChanceInfo chanceInfo = new ChanceInfo();
            JSONObject jsonObject1 = (JSONObject) object;
            String url2 = jsonObject1.getJSONObject("attributes").getString("url");
            String chanceId = url2.substring(url2.lastIndexOf("/") + 1);
            chanceInfo.setChanceId(chanceId);
            chanceInfo.setProjectId(jsonObject1.getString("Project_Name__c"));
            chanceInfo.setChanceName(jsonObject1.getString("Name"));
            chanceInfo.setPhase(jsonObject1.getString("StageName"));
            chanceInfo.setWinRate(new Double(jsonObject1.getString("Probability")));
            // chanceInfo.setQuantity(new Integer(jsonObject1.getString("")));
            //  DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            chanceInfo.setScheduledTime(jsonObject1.getString("CloseDate"));
            chanceInfo.setPrice(jsonObject1.getString("Amount_USD__c"));
            chanceInfo.setPo(jsonObject1.getString("SO_no__c"));
            list.add(chanceInfo);
        }

        return list;
    }

    private List<Customer> getCustomerList(String accessToken, String toExe)
    {
        String url =
                "https://cs76.salesforce.com/services/data/v37.0/query/?q=select+Acc_social_code__c, Account_Name__c, Contact_Phone__c,Account_Name__r.Name, Account_Name__r.Website, Account_Name__r.Phone, Account_Name__r.Billing_Address_Country__c, Account_Name__r.Billing_Address_State__c , Account_Name__r.Address_City_Picklist__c, Account_Name__r.Billing_Address_Street__c+from+B1000_project__c+where+LastModifiedDate+%3E%3D+" +
                        toExe;
        String message = b100Http.getData(url, accessToken);
        logger.info("CustomerList数据:" + message);
        JSONObject jsonObject = (JSONObject) JSONObject.parse(message);
        List list = new ArrayList();
        JSONArray jsonArray = jsonObject.getJSONArray("records");
        for (Object object : jsonArray)
        {
            Customer customer = new Customer();
            JSONObject jsonObject1 = (JSONObject) object;
            customer.setCustomerNo(jsonObject1.getString("Acc_social_code__c"));
            customer.setCustomerName(jsonObject1.getString("Account_Name__c"));
            customer.setPhone(jsonObject1.getString("Contact_Phone__c"));
            JSONObject jsonObject2 = jsonObject1.getJSONObject("Account_Name__r");
            if (ObjectUtils.isEmpty(jsonObject2))
            {
                continue;
            }
            customer.setName(jsonObject2.getString("Name"));
            customer.setSiteUrl(jsonObject2.getString("Website"));
            customer.setPhoneNumber(jsonObject2.getString("Phone"));
            customer.setAddressCountry(jsonObject2.getString("Billing_Address_Country__c"));
            customer.setAddressState(jsonObject2.getString("Billing_Address_State__c"));
            customer.setAddressCity(jsonObject2.getString("Address_City_Picklist__c"));
            customer.setAddressStreet(jsonObject2.getString("Billing_Address_Street__c"));
            list.add(customer);
        }
        return list;
    }

    private List<User> getUserList(String accessToken, String toExe, List<Project> projectList)
    {
        String url =
                "https://cs76.salesforce.com/services/data/v37.0/query/?q=select+ Project_name__c, Name, BID_email__c, BID_member__c, BID_Mobile__c, BPD_email__c, BPD_member__c, BPD_Mobile__c, CAD_email__c, CAD_member__c , CAD_Mobile__c, CMD_email__c , CMD_member__c, CMD_Mobile__c, CTD_email__c, CTD_member__c, CTD_Mobile__c, DSC_email__c, DSC_member__c, DSC_Mobile__c, GSD_email__c , GSD_member__c, GSD_Mobile__c , LSC_member__c, LSC_Mobile__c , HSC_email__c, HSC_member__c, HSC_Mobile__c, MSD_email__c, MSD_member__c, MSD_Mobile__c, PSD_email__c, PSD_member__c , PSD_Mobile__c, Service_member__c , Service_Mobile__c+from + B1000_project__c +where+LastModifiedDate+%3E%3D+" +
                        toExe;
        String message = b100Http.getData(url, accessToken);
        logger.info("UserList数据:" + message);
        JSONObject jsonObject = (JSONObject) JSONObject.parse(message);
        List<User> list = new ArrayList();
        JSONArray jsonArray = jsonObject.getJSONArray("records");
        for (Object object : jsonArray)
        {
            User user = new User();
            JSONObject jsonObject1 = (JSONObject) object;
            // // bid  bpd cad cmd csd ctd dsc  gsd   LSC mbd msd PSD  Service
            user.setProjectNo(jsonObject1.getString("Name"));
            user.setName(jsonObject1.getString("BPD_member__c"));
            user.setDepartmentCode("BPD");
            user.setDepartmentName("BPD");
            user.setPhone(jsonObject1.getString("BPD_Mobile__c"));
            user.setEmail(jsonObject1.getString("BPD_email__c"));
            list.add(user);
            User user2 = new User();
            user2.setProjectNo(jsonObject1.getString("Name"));
            user2.setName(jsonObject1.getString("BID_member__c"));
            user2.setDepartmentCode("BID");
            user2.setDepartmentName("BID");
            user2.setPhone(jsonObject1.getString("BID_Mobile__c"));
            user2.setEmail(jsonObject1.getString("BID_email__c"));
            list.add(user2);
            User user3 = new User();
            user3.setProjectNo(jsonObject1.getString("Name"));
            user3.setName(jsonObject1.getString("CAD_member__c"));
            user3.setDepartmentCode("CAD");
            user3.setDepartmentName("CAD");
            user3.setPhone(jsonObject1.getString("CAD_Mobile__c"));
            user3.setEmail(jsonObject1.getString("CAD_email__c"));
            list.add(user3);
            User user4 = new User();
            user4.setProjectNo(jsonObject1.getString("Name"));
            user4.setName(jsonObject1.getString("CMD_member__c"));
            user4.setDepartmentCode("CMD");
            user4.setDepartmentName("CMD");
            user4.setPhone(jsonObject1.getString("CMD_Mobile__c"));
            user4.setEmail(jsonObject1.getString("CMD_email__c"));
            list.add(user4);
            User user5 = new User();
            user5.setProjectNo(jsonObject1.getString("Name"));
            //  user5.setName(jsonObject1.getString("CSD_member__c"));
            user5.setDepartmentCode("CSD");
            user5.setDepartmentName("CSD");
            //user5.setPhone(jsonObject1.getString("CSD_Mobile__c"));
            // user5.setEmail(jsonObject1.getString("CSD_email__c"));
            list.add(user5);
            User user6 = new User();
            user6.setProjectNo(jsonObject1.getString("Name"));
            user6.setName(jsonObject1.getString("CTD_member__c"));
            user6.setDepartmentCode("CTD");
            user6.setDepartmentName("CTD");
            user6.setPhone(jsonObject1.getString("CTD_Mobile__c"));
            user6.setEmail(jsonObject1.getString("CTD_email__c"));
            list.add(user6);
            User user7 = new User();
            user7.setProjectNo(jsonObject1.getString("Name"));
            user7.setName(jsonObject1.getString("DSC_member__c"));
            user7.setDepartmentCode("DSC");
            user7.setDepartmentName("DSC");
            user7.setPhone(jsonObject1.getString("DSC_Mobile__c"));
            user7.setEmail(jsonObject1.getString("DSC_email__c"));
            list.add(user7);
            User user8 = new User();
            user8.setProjectNo(jsonObject1.getString("Name"));
            user8.setName(jsonObject1.getString("GSD_member__c"));
            user8.setDepartmentCode("GSD");
            user8.setDepartmentName("GSD");
            user8.setPhone(jsonObject1.getString("GSD_Mobile__c"));
            user8.setEmail(jsonObject1.getString("GSD_email__c"));
            list.add(user8);
            User user9 = new User();
            user9.setProjectNo(jsonObject1.getString("Name"));
            user9.setName(jsonObject1.getString("LSC_member__c"));
            user9.setDepartmentCode("LSC");
            user9.setDepartmentName("LSC");
            user9.setPhone(jsonObject1.getString("LSC_Mobile__c"));
            user9.setEmail(jsonObject1.getString("LSC_email__c"));
            list.add(user9);
            User user10 = new User();
            user10.setProjectNo(jsonObject1.getString("Name"));
            user10.setName(jsonObject1.getString("HSC_member__c"));
            user10.setDepartmentCode("HSC");
            user10.setDepartmentName("HSC");
            user10.setPhone(jsonObject1.getString("HSC_Mobile__c"));
            user10.setEmail(jsonObject1.getString("HSC_email__c"));
            list.add(user10);
            User user11 = new User();
            user11.setProjectNo(jsonObject1.getString("Name"));
            user11.setName(jsonObject1.getString("MSD_member__c"));
            user11.setDepartmentCode("MSD");
            user11.setDepartmentName("MSD");
            user11.setPhone(jsonObject1.getString("MSD_Mobile__c"));
            user11.setEmail(jsonObject1.getString("MSD_email__c"));
            list.add(user11);
            User user12 = new User();
            user12.setProjectNo(jsonObject1.getString("Name"));
            user12.setName(jsonObject1.getString("PSD_member__c"));
            user12.setDepartmentCode("PSD");
            user12.setDepartmentName("PSD");
            user12.setPhone(jsonObject1.getString("PSD_Mobile__c"));
            user12.setEmail(jsonObject1.getString("PSD_email__c"));
            list.add(user12);
            User user13 = new User();
            user13.setProjectNo(jsonObject1.getString("Name"));
            user13.setName(jsonObject1.getString("Service_member__c"));
            user13.setDepartmentCode("Service");
            user13.setDepartmentName("Service");
            user13.setPhone(jsonObject1.getString("Service_Mobile__c"));
            user13.setEmail(jsonObject1.getString("Service_email__c"));
            list.add(user13);
        }

        for (Project projct : projectList)
        {
            User user = new User();
            user.setProjectNo(projct.getProjectNo());
            user.setDepartmentCode(projct.getLeaderDivision());
            user.setDepartmentName(projct.getLeaderDivision());
            user.setName(projct.getProjectLeader());
            user.setPhone(projct.getLeaderMobile());
            user.setEmail(projct.getLeaderEmail());
            list.add(user);
        }

        return list;
    }

    private List<Estimate> getEstimateList(String accessToken, String toExe)
    {
        String url =
                "https://cs76.salesforce.com/services/data/v37.0/query/?q=select+name,BID_act_winrate__c, BID_booking__c, BID_email__c, BID_est_amount__c, BID_est_quantity__c , BID_est_winrate__c, BID_member__c, BID_Mobile__c, BID_Revenue__c, BPD_act_winrate__c , BPD_booking__c, BPD_email__c, BPD_est_amount__c, BPD_est_quantity__c, BPD_est_winrate__c , BPD_member__c, BPD_Mobile__c, BPD_Revenue__c, CAD_act_winrate__c, CAD_booking__c , CAD_email__c, CAD_est_amount__c, CAD_est_quantity__c, CAD_est_winrate__c, CAD_member__c , CAD_Mobile__c, CAD_revenue__c, CMD_act_winrate__c, CMD_booking__c, CMD_email__c , CMD_est_amount__c, CMD_est_quantity__c, CMD_est_winrate__c, CMD_member__c, CMD_Mobile__c , CMD_Revenue__c,CTD_act_winrate__c, CTD_booking__c, CTD_email__c, CTD_est_amount__c , CTD_est_quantity__c, CTD_est_winrate__c, CTD_member__c, CTD_Mobile__c, CTD_revenue__c , DSC_act_winrate__c, DSC_booking__c, DSC_email__c, DSC_est_amount__c , DSC_est_quantity__c, DSC_est_winrate__c, DSC_member__c, DSC_Mobile__c, DSC_revenue__c ,GSD_act_winrate__c, GSD_booking__c, GSD_email__c , GSD_est_amount__c, GSD_est_quantity__c, GSD_est_winrate__c, GSD_member__c, GSD_Mobile__c , GSD_Revenue__c, LSC_act_winrate__c, LSC_booking__c , LSC_est_amount__c, LSC_est_quantity__c, LSC_est_winrate__c, LSC_member__c, LSC_Mobile__c , LSC_Revenue__c, LSC_TPP_booking__c, LSC_TPP_est_amount__c, LSC_TPP_est_quan__c, LSC_TPP_revenue__c , LSCTPP_est_winrate__c, HSC_booking__c, HSC_email__c, HSC_est_amount__c , HSC_est_quantity__c, HSC_est_winrate__c, HSC_member__c,HSC_Mobile__c, HSC_revenue__c  , MSD_act_winrate__c, MSD_booking__c, MSD_email__c, MSD_est_amount__c, MSD_est_quantity__c , MSD_est_winrate__c, MSD_member__c, MSD_Mobile__c, MSD_revenue__c, PSD_act_winrate__c, PSD_booking__c , PSD_email__c, PSD_est_amount__c, PSD_est_quantity__c, PSD_est_winrate__c, PSD_member__c , PSD_Mobile__c, PSD_Revenue__c, Service_act_winrate__c , Service_booking__c, Service_est_amount__c, Service_est_quantity__c, Service_est_winrate__c, Service_member__c , Service_Mobile__c, Service_Revenue__c+from+B1000_project__c+where+LastModifiedDate+%3E%3D+" +
                        toExe;
        String message = b100Http.getData(url, accessToken);
        logger.info("EstimateList数据:" + message);
        JSONObject jsonObject = (JSONObject) JSONObject.parse(message);
        List list = new ArrayList();
        JSONArray jsonArray = jsonObject.getJSONArray("records");
        for (Object object : jsonArray)
        {
            Estimate estimate = new Estimate();
            JSONObject jsonObject1 = (JSONObject) object;
            // bid  bpd cad cmd csd ctd dsc  gsd   LSC mbd msd PSD  Service
            estimate.setProjectNo(jsonObject1.getString("Name"));
            estimate.setEstQuantity(jsonObject1.getString("BID_est_quantity__c"));
            estimate.setEstAmount(jsonObject1.getString("BID_est_amount__c"));
            if (!StringUtils.isEmpty(jsonObject1.getString("BID_est_winrate__c")))
            {
                estimate.setEstWinrate(jsonObject1.getString("BID_est_winrate__c"));
            }

            estimate.setDepartmentNo("BID");
            estimate.setDepartmentName("BID");
            estimate.setEstBooking(jsonObject1.getString(""));
            estimate.setActBooking(jsonObject1.getString("BID_booking__c"));
            estimate.setActRevenue(jsonObject1.getString("BID_revenue__c"));
            estimate.setActQuantity(jsonObject1.getString(""));
            estimate.setActWinrate(jsonObject1.getString("BID_act_winrate__c"));
            estimate.setActAmount(jsonObject1.getString(""));
            list.add(estimate);
            Estimate estimate2 = new Estimate();
            estimate2.setProjectNo(jsonObject1.getString("Name"));
            estimate2.setEstQuantity(jsonObject1.getString("BPD_est_quantity__c"));
            estimate2.setEstAmount(jsonObject1.getString("BPD_est_amount__c"));
            if (!StringUtils.isEmpty(jsonObject1.getString("BPD_est_winrate__c")))
            {
                estimate2.setEstWinrate(jsonObject1.getString("BPD_est_winrate__c"));
            }

            estimate2.setDepartmentNo("BPD");
            estimate2.setDepartmentName("BPD");
            estimate2.setEstBooking(jsonObject1.getString(""));
            estimate2.setActBooking(jsonObject1.getString("BPD_booking__c"));
            estimate2.setActRevenue(jsonObject1.getString("BPD_revenue__c"));
            estimate2.setActQuantity(jsonObject1.getString(""));
            estimate2.setActWinrate(jsonObject1.getString("BPD_act_winrate__c"));
            estimate2.setActAmount(jsonObject1.getString(""));
            list.add(estimate2);
            Estimate estimate3 = new Estimate();
            estimate3.setProjectNo(jsonObject1.getString("Name"));
            estimate3.setEstQuantity(jsonObject1.getString("CAD_est_quantity__c"));
            estimate3.setEstAmount(jsonObject1.getString("CAD_est_amount__c"));
            if (!StringUtils.isEmpty(jsonObject1.getString("CAD_est_winrate__c")))
            {
                estimate3.setEstWinrate(jsonObject1.getString("CAD_est_winrate__c"));
            }
            ;
            estimate3.setDepartmentNo("CAD");
            estimate3.setDepartmentName("CAD");
            estimate3.setEstBooking(jsonObject1.getString(""));
            estimate3.setActBooking(jsonObject1.getString("CAD_booking__c"));
            estimate3.setActRevenue(jsonObject1.getString("CAD_revenue__c"));
            estimate3.setActQuantity(jsonObject1.getString(""));
            estimate3.setActWinrate(jsonObject1.getString("CAD_act_winrate__c"));
            estimate3.setActAmount(jsonObject1.getString(""));
            list.add(estimate3);
            Estimate estimate4 = new Estimate();
            estimate4.setProjectNo(jsonObject1.getString("Name"));
            estimate4.setEstQuantity(jsonObject1.getString("CMD_est_quantity__c"));
            estimate4.setEstAmount(jsonObject1.getString("CMD_est_amount__c"));
            if (!StringUtils.isEmpty(jsonObject1.getString("CMD_est_winrate__c")))
            {
                estimate4.setEstWinrate(jsonObject1.getString("CMD_est_winrate__c"));
            }
            ;
            estimate4.setDepartmentNo("CMD");
            estimate4.setDepartmentName("CMD");
            estimate4.setEstBooking(jsonObject1.getString(""));
            estimate4.setActBooking(jsonObject1.getString("CMD_booking__c"));
            estimate4.setActRevenue(jsonObject1.getString("CMD_revenue__c"));
            estimate4.setActQuantity(jsonObject1.getString(""));
            estimate4.setActWinrate(jsonObject1.getString("CMD_act_winrate__c"));
            estimate4.setActAmount(jsonObject1.getString(""));
            list.add(estimate4);
            Estimate estimate5 = new Estimate();
            estimate5.setProjectNo(jsonObject1.getString("Name"));
            // estimate5.setEstQuantity(jsonObject1.getString("CSD_est_quantity__c"));
            //estimate5.setEstAmount(jsonObject1.getString("CSD_est_amount__c"));
//            if (!StringUtils.isEmpty(jsonObject1.getString("CSD_est_winrate__c")))
//            {
//                estimate5.setEstWinrate(jsonObject1.getString("CSD_est_winrate__c"));
//            }
//            ;
            estimate5.setDepartmentNo("CSD");
            estimate5.setDepartmentName("CSD");
            estimate5.setEstBooking(jsonObject1.getString(""));
            // estimate5.setActBooking(jsonObject1.getString("CSD_booking__c"));
            // estimate5.setActRevenue(jsonObject1.getString("CSD_revenue__c"));
            estimate5.setActQuantity(jsonObject1.getString(""));
            // estimate5.setActWinrate(jsonObject1.getString("CSD_act_winrate__c"));
            estimate5.setActAmount(jsonObject1.getString(""));
            list.add(estimate5);
            Estimate estimate6 = new Estimate();
            estimate6.setProjectNo(jsonObject1.getString("Name"));
            estimate6.setEstQuantity(jsonObject1.getString("CTD_est_quantity__c"));
            estimate6.setEstAmount(jsonObject1.getString("CTD_est_amount__c"));
            if (!StringUtils.isEmpty(jsonObject1.getString("CTD_est_winrate__c")))
            {
                estimate6.setEstWinrate(jsonObject1.getString("CTD_est_winrate__c"));
            }
            ;
            estimate6.setDepartmentNo("CTD");
            estimate6.setDepartmentName("CTD");
            estimate6.setEstBooking(jsonObject1.getString(""));
            estimate6.setActBooking(jsonObject1.getString("CTD_booking__c"));
            estimate6.setActRevenue(jsonObject1.getString("CTD_revenue__c"));
            estimate6.setActQuantity(jsonObject1.getString(""));
            estimate6.setActWinrate(jsonObject1.getString("CTD_act_winrate__c"));
            estimate6.setActAmount(jsonObject1.getString(""));
            list.add(estimate6);
            Estimate estimate7 = new Estimate();
            estimate7.setProjectNo(jsonObject1.getString("Name"));
            estimate7.setEstQuantity(jsonObject1.getString("DSC_est_quantity__c"));
            estimate7.setEstAmount(jsonObject1.getString("DSC_est_amount__c"));
            if (!StringUtils.isEmpty(jsonObject1.getString("DSC_est_winrate__c")))
            {
                estimate7.setEstWinrate(jsonObject1.getString("DSC_est_winrate__c"));
            }
            ;
            estimate7.setDepartmentNo("DSC");
            estimate7.setDepartmentName("DSC");
            estimate7.setEstBooking(jsonObject1.getString(""));
            estimate7.setActBooking(jsonObject1.getString("DSC_booking__c"));
            estimate7.setActRevenue(jsonObject1.getString("DSC_revenue__c"));
            estimate7.setActQuantity(jsonObject1.getString(""));
            estimate7.setActWinrate(jsonObject1.getString("DSC_act_winrate__c"));
            estimate7.setActAmount(jsonObject1.getString(""));
            list.add(estimate7);
            Estimate estimate8 = new Estimate();
            estimate8.setProjectNo(jsonObject1.getString("Name"));
            if (!StringUtils.isEmpty(jsonObject1.getString("GSD_est_quantity__c")))
            {
                estimate8.setEstQuantity(jsonObject1.getString("GSD_est_quantity__c"));
            }

            if (!StringUtils.isEmpty(jsonObject1.getString("GSD_est_amount__c")))
            {
                estimate8.setEstAmount(jsonObject1.getString("GSD_est_amount__c"));
            }

            if (!StringUtils.isEmpty(jsonObject1.getString("GSD_est_winrate__c")))
            {
                estimate.setEstWinrate(jsonObject1.getString("GSD_est_winrate__c"));
            }
            ;
            estimate8.setDepartmentNo("GSD");
            estimate8.setDepartmentName("GSD");
            estimate8.setEstBooking(jsonObject1.getString(""));
            estimate8.setActBooking(jsonObject1.getString("GSD_booking__c"));
            estimate8.setActRevenue(jsonObject1.getString("GSD_revenue__c"));
            estimate8.setActQuantity(jsonObject1.getString(""));
            estimate8.setActWinrate(jsonObject1.getString("GSD_act_winrate__c"));
            estimate8.setActAmount(jsonObject1.getString(""));
            list.add(estimate8);
            Estimate estimate9 = new Estimate();
            estimate9.setProjectNo(jsonObject1.getString("Name"));
            if (!StringUtils.isEmpty(jsonObject1.getString("LSC_est_quantity__c")))
            {
                estimate9.setEstQuantity(jsonObject1.getString("LSC_est_quantity__c"));
            }
            if (!StringUtils.isEmpty(jsonObject1.getString("LSC_est_amount__c")))
            {
                estimate9.setEstAmount(jsonObject1.getString("LSC_est_amount__c"));
            }
            if (!StringUtils.isEmpty(jsonObject1.getString("LSC_est_winrate__c")))
            {
                estimate9.setEstWinrate(jsonObject1.getString("LSC_est_winrate__c"));
            }
            ;
            estimate9.setDepartmentNo("LSC");
            estimate9.setDepartmentName("LSC");
            estimate9.setEstBooking(jsonObject1.getString(""));
            estimate9.setActBooking(jsonObject1.getString("LSC_booking__c"));
            estimate9.setActRevenue(jsonObject1.getString("LSC_Revenue__c"));
            estimate9.setActQuantity(jsonObject1.getString(""));
            estimate9.setActWinrate(jsonObject1.getString("LSC_act_winrate__c"));
            estimate9.setActAmount(jsonObject1.getString(""));
            list.add(estimate9);
            Estimate estimate10 = new Estimate();
            estimate10.setProjectNo(jsonObject1.getString("Name"));
            if (!StringUtils.isEmpty(jsonObject1.getString("HSC_est_quantity__c")))
            {
                estimate10.setEstQuantity(jsonObject1.getString("HSC_est_quantity__c"));
            }

            if (!StringUtils.isEmpty(jsonObject1.getString("HSC_est_amount__c")))
            {
                estimate10.setEstAmount(jsonObject1.getString("HSC_est_amount__c"));
            }

            if (!StringUtils.isEmpty(jsonObject1.getString("HSC_est_winrate__c")))
            {
                estimate10.setEstWinrate(jsonObject1.getString("HSC_est_winrate__c"));
            }
            ;
            estimate10.setDepartmentNo("HSC");
            estimate10.setDepartmentName("HSC");
            estimate10.setEstBooking(jsonObject1.getString(""));
            estimate10.setActBooking(jsonObject1.getString("HSC_booking__c"));
            estimate10.setActRevenue(jsonObject1.getString("HSC_revenue__c"));
            estimate10.setActQuantity(jsonObject1.getString(""));
            //estimate10.setActWinrate(jsonObject1.getString("HSC_act_winrate__c"));
            estimate10.setActAmount(jsonObject1.getString(""));
            list.add(estimate10);
            Estimate estimate11 = new Estimate();
            estimate11.setProjectNo(jsonObject1.getString("Name"));
            estimate11.setEstQuantity(jsonObject1.getString("MSD_est_quantity__c"));
            estimate11.setEstAmount(jsonObject1.getString("MSD_est_amount__c"));
            if (!StringUtils.isEmpty(jsonObject1.getString("MSD_est_winrate__c")))
            {
                estimate11.setEstWinrate(jsonObject1.getString("MSD_est_winrate__c"));
            }
            ;
            estimate11.setDepartmentNo("MSD");
            estimate11.setDepartmentName("MSD");
            estimate11.setEstBooking(jsonObject1.getString(""));
            estimate11.setActBooking(jsonObject1.getString("MSD_booking__c"));
            estimate11.setActRevenue(jsonObject1.getString("MSD_revenue__c"));
            estimate11.setActQuantity(jsonObject1.getString(""));
            estimate11.setActWinrate(jsonObject1.getString("MSD_act_winrate__c"));
            estimate11.setActAmount(jsonObject1.getString(""));
            list.add(estimate11);
            Estimate estimate12 = new Estimate();
            estimate12.setProjectNo(jsonObject1.getString("Name"));
            estimate12.setEstQuantity(jsonObject1.getString("PSD_est_quantity__c"));
            estimate12.setEstAmount(jsonObject1.getString("PSD_est_amount__c"));
            if (!StringUtils.isEmpty(jsonObject1.getString("PSD_est_winrate__c")))
            {
                estimate12.setEstWinrate(jsonObject1.getString("PSD_est_winrate__c"));
            }
            ;
            estimate12.setDepartmentNo("PSD");
            estimate12.setDepartmentName("PSD");
            estimate12.setEstBooking(jsonObject1.getString(""));
            estimate12.setActBooking(jsonObject1.getString("PSD_booking__c"));
            estimate12.setActRevenue(jsonObject1.getString("PSD_revenue__c"));
            estimate12.setActQuantity(jsonObject1.getString(""));
            estimate12.setActWinrate(jsonObject1.getString("PSD_act_winrate__c"));
            estimate12.setActAmount(jsonObject1.getString(""));
            list.add(estimate12);
            Estimate estimate13 = new Estimate();
            estimate13.setProjectNo(jsonObject1.getString("Name"));
            if (!StringUtils.isEmpty(jsonObject1.getString("Service_est_quantity__c")))
            {
                estimate13.setEstQuantity(jsonObject1.getString("Service_est_quantity__c"));
            }
            if (!StringUtils.isEmpty(jsonObject1.getString("Service_est_amount__c")))
            {
                estimate13.setEstAmount(jsonObject1.getString("Service_est_amount__c"));
            }

            if (!StringUtils.isEmpty(jsonObject1.getString("Service_est_winrate__c")))
            {
                estimate13.setEstWinrate(jsonObject1.getString("Service_est_winrate__c"));
            }
            ;
            estimate13.setDepartmentNo("Service");
            estimate13.setDepartmentName("Service");
            estimate13.setEstBooking(jsonObject1.getString(""));
            estimate13.setActBooking(jsonObject1.getString("Service_booking__c"));
            estimate13.setActRevenue(jsonObject1.getString("Service_Revenue__c"));
            estimate13.setActQuantity(jsonObject1.getString(""));
            estimate13.setActWinrate(jsonObject1.getString("Service_act_winrate__c"));
            estimate13.setActAmount(jsonObject1.getString(""));
            list.add(estimate13);
        }
        return list;
    }

    private List<Project> getProjectList(String accessToken, String toExe)
    {
        String url =
                "https://cs76.salesforce.com/services/data/v37.0/query/?q=select+Id," +
                        "LastModifiedDate ,CreatedDate ,Project_name__c ,Project_Competitor__c," +
                        "Account_Name__r.Name_Chinese__c ,Name ,Project_type__c ," +
                        "Project_subtype__c ,Account_Name__r.Name, Project_status__c ,Approve_status__c ,Project_description__c ,Project_sponsor__c ,Project_sponsor__r.name,Project_leader__r.name,Project_approver__r.name,Sponsor_division__c ,Sponsor_mobile__c ,Project_approver__c ,Approver_division__c ,Approver_mobile__c ,Project_leader__c ,Leader_division__c ,Leader_Email__c,Leader_mobile__c ,Est_initiate_date__c ,Est_order_date__c ,Est_bid_date__c ,Est_arrival_date__c ,Project_amount__c ,Est_tmo_amount__c ,Project_winrate__c ,Project_division__c ,Acc_social_code__c ,Project_city__c,BID_booking__c ,BPD_booking__c ,CAD_booking__c ,CMD_booking__c,CTD_booking__c ,DSC_booking__c ,GSD_booking__c ,LSC_booking__c ,HSC_booking__c ,MSD_booking__c ,PSD_booking__c ,Service_booking__c ,BID_est_amount__c ,BPD_est_amount__c ,CAD_est_amount__c ,CMD_est_amount__c,CTD_est_amount__c ,DSC_est_amount__c ,GSD_est_amount__c ,LSC_est_amount__c ,HSC_est_amount__c ,PSD_est_amount__c ,Service_est_amount__c ,BID_revenue__c ,HSC_revenue__c ,CAD_revenue__c ,CMD_revenue__c,CTD_revenue__c ,DSC_revenue__c ,GSD_revenue__c ,LSC_revenue__c ,MSD_revenue__c ,PSD_revenue__c ,Service_revenue__c+from+B1000_project__c+where+LastModifiedDate+%3E%3D" +
                        toExe;
        String message = b100Http.getData(url, accessToken);
        List pubList = new ArrayList();
        List list = new ArrayList();
        logger.info("ProjectList数据:" + message);
        JSONObject jsonObject = (JSONObject) JSONObject.parse(message);
        JSONArray jsonArray = jsonObject.getJSONArray("records");
        for (Object object : jsonArray)
        {
            Project project = new Project();
            Map map = new HashMap();
            JSONObject jsonObject1 = (JSONObject) object;
            project.setProjectId(jsonObject1.getString("Id"));
            project.setProjectNo(jsonObject1.getString("Name"));
            project.setProjectName(jsonObject1.getString("Project_name__c"));
            project.setProjectType(jsonObject1.getString("Project_type__c"));
            project.setProjectSubtype(jsonObject1.getString("Project_subtype__c"));
            project.setProjectStatus(jsonObject1.getString("Project_status__c"));
            project.setLocation(jsonObject1.getString(""));
            project.setCompetitor(jsonObject1.getString("Project_Competitor__c"));
            project.setCreatedDate(jsonObject1.getString("CreatedDate"));
            if (!ObjectUtils.isEmpty(jsonObject1.getJSONObject("Account_Name__r")))
            {
                project.setCompanyName(
                        jsonObject1.getJSONObject("Account_Name__r").getString("Name_Chinese__c"));
            }
            project.setApproveStatus(jsonObject1.getString("Approve_status__c"));
            project.setProjectDescription(jsonObject1.getString("Project_description__c"));
            if (!ObjectUtils.isEmpty(jsonObject1.getJSONObject("Project_sponsor__r")))
            {
                project.setProjectSponsor(
                        jsonObject1.getJSONObject("Project_sponsor__r").getString("Name"));
            }
            project.setSponsorDivision(jsonObject1.getString("Sponsor_division__c"));
            project.setSponsorMobile(jsonObject1.getString("Sponsor_mobile__c"));
            if (!ObjectUtils.isEmpty(jsonObject1.getJSONObject("Project_approver__r")))
            {
                project.setProjectApprover(
                        jsonObject1.getJSONObject("Project_approver__r").getString("Name"));
            }
            project.setApproverDivision(jsonObject1.getString("Approver_division__c"));
            project.setApproverMobile(jsonObject1.getString("Approver_mobile__c"));
            if (!ObjectUtils.isEmpty(jsonObject1.getJSONObject("Project_leader__r")))
            {
                project.setProjectLeader(
                        jsonObject1.getJSONObject("Project_leader__r").getString("Name"));
            }
            project.setLeaderDivision(jsonObject1.getString("Leader_division__c"));
            project.setLeaderEmail(jsonObject1.getString("Leader_Email__c"));

            project.setLeaderMobile(jsonObject1.getString("Leader_mobile__c"));
            project.setEstInitiateDate(jsonObject1.getString("Est_initiate_date__c"));
            project.setEstSignDate(jsonObject1.getString("Est_order_date__c"));
            project.setEstBidDate(jsonObject1.getString("Est_bid_date__c"));
            project.setEstArrivalDate(jsonObject1.getString("Est_arrival_date__c"));
            if (!StringUtils.isEmpty(jsonObject1.getString("Project_amount__c")))
            {
                project.setProjectAmount(jsonObject1.getString("Project_amount__c"));
            }
            project.setEstTmoAmount(jsonObject1.getString("Est_tmo_amount__c"));
            if (!StringUtils.isEmpty(jsonObject1.getString("Project_winrate__c")))
            {
                project.setProjectWinrate(jsonObject1.getString("Project_winrate__c"));
            }
            project.setProjectDivision(jsonObject1.getString("Project_division__c"));
            project.setProjectSource(jsonObject1.getString(" "));
            project.setCustomerNo(jsonObject1.getString("Acc_social_code__c"));
            project.setCompanySupport(jsonObject1.getString(""));
            project.setCity(jsonObject1.getString("Project_city__c"));
            project.setSubSupport(jsonObject1.getString("Project_subtype__c"));
            project.setProvince(jsonObject1.getString(""));
            project.setArea(jsonObject1.getString(""));
            project.setLastModifiedDate(jsonObject1.getString("LastModifiedDate"));
            Map<String, BigDecimal> mapTotal = getTotalDecimal(jsonObject1);
            BigDecimal book = mapTotal.get("book");
            BigDecimal estAmount = mapTotal.get("estAmount");
            BigDecimal revenue = mapTotal.get("revenue");
            BigDecimal winrate = new BigDecimal("0.0");
            project.setBooking(String.valueOf(book));
            project.setEstAmount(String.valueOf(estAmount));
            project.setRevenue(String.valueOf(revenue));
            if (!StringUtils.isEmpty(jsonObject1.getString("Est_tmo_amount__c")) &&
                    !StringUtils.equals("0.0", jsonObject1.getString("Est_tmo_amount__c")))
            {
                winrate = revenue
                        .divide(new BigDecimal(jsonObject1.getString("Est_tmo_amount__c")), 2);
            }
            project.setWinrate(String.valueOf(winrate));
            list.add(project);
        }
        return list;
    }

    private Map<String, BigDecimal> getTotalDecimal(JSONObject jsonObject)
    {
        Map<String, String> params = JSONObject
                .parseObject(jsonObject.toJSONString(), new TypeReference<Map<String, String>>()
                {
                });
        Map<String, BigDecimal> map = new HashMap();
        BigDecimal book = new BigDecimal("0.0");
        BigDecimal estAmount = new BigDecimal("0.0");
        BigDecimal revenue = new BigDecimal("0.0");

        for (Map.Entry<String, String> entry : params.entrySet())
        {
            if (entry.getKey().indexOf("_booking__c") != -1 &&
                    StringUtils.isNotEmpty(entry.getValue()) && isBigDecimal(entry.getValue()))
            {
                book = book.add(new BigDecimal(entry.getValue()));
            }
            if (entry.getKey().indexOf("_est_amount__c") != -1 &&
                    StringUtils.isNotEmpty(entry.getValue()) && isBigDecimal(entry.getValue()))
            {
                estAmount = estAmount.add(new BigDecimal(entry.getValue()));
            }
            if ((entry.getKey().indexOf("_revenue__c") != -1 ||
                    entry.getKey().indexOf("_Revenue__c") != -1) &&
                    StringUtils.isNotEmpty(entry.getValue()) && isBigDecimal(entry.getValue()))
            {
                revenue = revenue.add(new BigDecimal(entry.getValue()));
            }
        }
        map.put("book", book);
        map.put("estAmount", estAmount);
        map.put("revenue", revenue);
        return map;
    }

    public static boolean isBigDecimal(String str)
    {
        if (str == null || str.trim().length() == 0)
        {
            return false;
        }
        char[] chars = str.toCharArray();
        int sz = chars.length;
        int i = (chars[0] == '-') ? 1 : 0;
        if (i == sz)
            return false;

        if (chars[i] == '.')
            return false;//除了负号，第一位不能为'小数点'

        boolean radixPoint = false;
        for (; i < sz; i++)
        {
            if (chars[i] == '.')
            {
                if (radixPoint)
                    return false;
                radixPoint = true;
            }
            else if (!(chars[i] >= '0' && chars[i] <= '9'))
            {
                return false;
            }
        }
        return true;
    }

    private String getToken()
    {
        String url1 = "https://test.salesforce.com/services/oauth2/token";
        Map map1 = new HashMap();
        map1.put("client_id",
                 "3MVG9N6eDmZRVJOnbnGA3SU5MvLScUAsYkDqPCxdYPOaWIgYghpGvy_gJ1MbTVG54qpSoO3bVoP1rN8sqR3N7");
        map1.put("client_secret",
                 "6123D4E8A3B184879760BFA55653CB85D27956C2F31FF383D698A79DA5FAA832");
        map1.put("username", "integration@thermofisher.com.full");
        map1.put("password", "Integr@ti0nOgPem9TaMItiNO0fIl1eJqpt");
        map1.put("grant_type", "password");
        String message = b100Http.getToker(url1, map1);
        if (StringUtils.isEmpty(message))
        {
            return null;
        }
        //String accessToken = ((JsonObject) new JsonParser().parse(message)).get("access_token").toString().replaceAll("\"", "");
        String accessToken = JSONObject.parseObject(message).getString("access_token")
                .replaceAll("\"", "");
        return accessToken;
    }

    private Config init()
    {
        Config config = configService.getOne(
                Wrappers.<Config>lambdaQuery()
                        .eq(Config::getPublicKey, "update_time"));
        if (ObjectUtils.isEmpty(config))
        {
            config = getConfig(config);
            configService.save(config);
        }
        if (ObjectUtils.isEmpty(config.getValue()))
        {
            updateConfig(config, null);
            configService.saveOrUpdate(config);
        }
        return config;
    }

    private Config getConfig(Config config)
    {
        config = new Config();
        config.setPublicKey("update_time");
        return config;
    }

    private void updateConfig(Config config, String now)
    {
        if (StringUtils.isEmpty(now))
        {
            now = getNow();
        }
        config.setValue(now);
    }

    private String getNow()
    {
        String now = configService.getNow();
        String hour = now.substring(11, 13);
        Integer time = Integer.parseInt(hour);
        time = 4 * (time / 4);
        if (time < 10)
        {
            now = now.substring(0, 11) + "0" + time + ":00:00Z";
        }
        else
        {
            now = now.substring(0, 11) + time + ":00:00Z";
        }
        return now;
    }

}
